<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      // 幂集算法
      // https://gitee.com/Megasu/javascript-algorithms/tree/master/src/algorithms/sets/power-set
      function bwPowerSet(originalSet) {
        const subSets = []

        // We will have 2^n possible combinations (where n is a length of original set).
        // It is because for every element of original set we will decide whether to include
        // it or not (2 options for each set element).
        const numberOfCombinations = 2 ** originalSet.length

        // Each number in binary representation in a range from 0 to 2^n does exactly what we need:
        // it shows by its bits (0 or 1) whether to include related element from the set or not.
        // For example, for the set {1, 2, 3} the binary number of 0b010 would mean that we need to
        // include only "2" to the current set.
        for (let combinationIndex = 0; combinationIndex < numberOfCombinations; combinationIndex += 1) {
          const subSet = []

          for (let setElementIndex = 0; setElementIndex < originalSet.length; setElementIndex += 1) {
            // Decide whether we need to include current element into the subset or not.
            if (combinationIndex & (1 << setElementIndex)) {
              subSet.push(originalSet[setElementIndex])
            }
          }

          // Add current subset to the list of all subsets.
          subSets.push(subSet)
        }

        return subSets
      }
    </script>
  </head>
  <body>
    <script>
      // 通过幂集算法帮我们处理字典
      const res = bwPowerSet(['蓝色', '中国', '10cm'])
      // console.log(res)
      // 算法库处理结果： [ [], [ "蓝色" ], [ "中国" ], [ "蓝色", "中国" ], [ "10cm" ], [ "蓝色", "10cm" ], [ "中国", "10cm" ], [ "蓝色", "中国", "10cm" ] ]
      const arr = []
      res.forEach(item => {
        // 把返回值处理成字符串方便后续查找
        arr.push(item.join('★'))
      })
      // 字符串化结果：['', '蓝色', '中国', '蓝色★中国', '10cm', '蓝色★10cm', '中国★10cm', '蓝色★中国★10cm']
      

      
      const res2 = bwPowerSet(['黑色', '中国', '10cm'])
      const arr2 = []
      res2.forEach(item => {
        // 把返回值处理成字符串方便后续查找
        arr2.push(item.join('★'))
      })



      console.log(arr)
      console.log(arr2)
    </script>
  </body>
</html>
